package com.itboye.ihomebank.adapter;

import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.me.AuthorIngActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.WoDeFangYuanBean;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.activity.home.ActivityRenZheng;
import com.itboye.ihomebank.activity.home.ActivityRenZhengZhong;
import com.itboye.ihomebank.activity.home.ActivityXuanZuKe;
import com.itboye.ihomebank.activity.home.YuYueZuKeDetail;
import com.itboye.ihomebank.activity.homefragment.ActivityFuYongOne;
import com.itboye.ihomebank.activity.home.ActivityEditHouse;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.support.commonadapter.MutiplyCommonAdapter;
import com.itboye.ihomebank.support.commonadapter.ViewHolder;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.LoadingDialog;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.UIAlertView;
import com.itboye.ihomebank.util.WriteZhangHaoPopupWindow;
import com.itboye.ihomebank.util.XImageLoader;

import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;


/**
 * 我的房源
 * 
 */
public class WodeFangyYuanAdapter extends
		MutiplyCommonAdapter<WoDeFangYuanBean> implements Observer {
	Activity activity;
	HousePresenter housePresenter;
	protected String uid;
	String tempHouseNo;
	String tempContractNo;
	List<WoDeFangYuanBean> datas;
	protected WriteZhangHaoPopupWindow mCameraPopupWindow;
	EditText pass;
	protected String money;
	String role;
	private UIAlertView uiAlertView;
	LoadingDialog loadDialog;
	public static int WodeFangyYuanAdapter_REQUEST=2;
	public void setRole(String role) {
		this.role = role;
	}

	public WodeFangyYuanAdapter(Activity context, List<WoDeFangYuanBean> datas,
			int... layoutId) {
		super(context, datas, layoutId);
		activity = context;
		housePresenter = new HousePresenter(this);
		uid = SPUtils.get(activity, null, SPContants.USER_ID, "") + "";
		this.datas = datas;
	}

	@Override
	public int getItemViewType(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void getItemPosition(int position) {
		// TODO Auto-generated method stub

	}

	@Override
	public void convert(ViewHolder holder, final WoDeFangYuanBean t, int type,
			int position) {
		if (t != null) {

			holder.setText(R.id.house_name, t.getTitle());

			holder.setText(R.id.addr, t.getHouseRoom()+"室"+t.getHouseHall()+"厅/"+t.getHouseArea()+"㎡/"+t.getHouseDir());
			holder.setText(R.id.house_price, "¥"+Double.parseDouble(t.getRent())
					/ 100 + "元/月");
			XImageLoader.load(NetPublicConstant.IMAGE_URL + t.getImgId(),
					(ImageView) holder.getView(R.id.img_top));
			holder.setText(R.id.other, t.getApply() + "位租客已经申请租房");
			if (t.getContractNo().equals("")) {//为空则表示签约未完成

			}else{
				holder.setVisible(R.id.house_tag,true);
			}
			String biao01 = t.getTags();
			String[] str = {};
			if (biao01 != null) {
				str = biao01.split(",");
			}
			/**
			 * 已认证：选租客、选预约、刷新、上下架 未认证：认证、刷新、下架 为选租客
			 */
			holder.setTag(R.id.xuanzuke, t.getTagId());
			if (t.getStatus().equals("1")) {// status为房源状态，1为上架，2为下架，-1为删除
				holder.setText(R.id.xiajia, "下架");
				if (t.getTagId().equals("0")) {// tag_id 为房源认证状态，0为未认证 1为已认证
					holder.setVisible(R.id.shuaxin, true);
					holder.setVisible(R.id.certified,false);
					if(t.getVerify_status().equals("1")){ //verify_status 0 为其他 1为认证中
						holder.setText(R.id.renzheng,"认证中");
					}
					holder.setVisible(R.id.renzheng, true);
					holder.setVisible(R.id.xiajia, true);
					holder.setVisible(R.id.xuanzuke, false);
					holder.setVisible(R.id.xuanyuyue, true);
//					holder.setVisible(R.id.fuyong, false);
					holder.setText(R.id.xuanyuyue, "修改");
				} else if (t.getTagId().equals("1")) {
					holder.setVisible(R.id.renzheng, false);
					holder.setVisible(R.id.certified,true);
//					holder.setVisible(R.id.fuyong, false);
					holder.setVisible(R.id.xuanyuyue, false);
					holder.setVisible(R.id.xuanzuke, true);
					holder.setVisible(R.id.shuaxin, true);
					holder.setText(R.id.xuanzuke, "选租客");
					holder.setVisible(R.id.xiajia, true);
				}
			} else if (t.getStatus().equals("2")) {
				if (t.getTagId().equals("0")) {// tag_id 为房源认证状态，0为未认证 1为已认证
					holder.setVisible(R.id.certified,false);
				}else if (t.getTagId().equals("1")){

					holder.setVisible(R.id.certified,true);
				}

				holder.setVisible(R.id.shuaxin, false);
				holder.setVisible(R.id.xuanzuke, false);
				holder.setVisible(R.id.renzheng, false);
//				if (Integer.parseInt(t.getApply()) <= 0) {
					holder.setText(R.id.xuanyuyue, "删除");
					holder.setVisible(R.id.xuanyuyue, true);
//				}else{
//					holder.setVisible(R.id.xuanyuyue, false);
//				}
//				holder.setVisible(R.id.fuyong, false);
				holder.setVisible(R.id.xiajia, true);
				holder.setText(R.id.xiajia, "上架");
			} else if (t.getStatus().equals("-1")) {
				holder.setText(R.id.xiajia, "已删除");
			} else if (t.getStatus().equals("3")) {// 已经选择租客
				holder.setVisible(R.id.renzheng, false);
				holder.setVisible(R.id.xuanyuyue, false);
//				holder.setVisible(R.id.fuyong, true);
				holder.setVisible(R.id.xuanzuke, true);
				holder.setVisible(R.id.shuaxin, false);
				holder.setVisible(R.id.xiajia, false);
				holder.setText(R.id.xuanzuke, "查看租客信息");
				holder.setText(R.id.other, "已选租客");
			}

		}
		String[] str=null;
		if (t.getTags() != null) {
			holder.removeAllViewsLinearLayout(R.id.tag);
			if (t.getTags().equals("")) {
				holder.setVisible(R.id.tag,false);
			} else if (t.getTags().contains(",")) {
				str = t.getTags().split(",");

				for (int i = 0; i < str.length; i++) {
					View innerView = LayoutInflater.from(MyApplcation.ctx)
							.inflate(R.layout.item_biaoqian, null);
					TextView btn_name = (TextView) innerView
							.findViewById(R.id.btn_name);
					btn_name.setText(str[i]);
					btn_name.setTextSize(13);
					btn_name.setPadding(10,5,10,5);
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.WRAP_CONTENT,
							LinearLayout.LayoutParams.WRAP_CONTENT);
					layoutParams.setMargins(5, 5, 5, 5);
					innerView.setLayoutParams(layoutParams);
					holder.addViewLinearLayout(R.id.tag,innerView);
				}

			} else {
				View innerView = LayoutInflater.from(MyApplcation.ctx).inflate(
						R.layout.item_biaoqian, null);
				TextView btn_name = (TextView) innerView
						.findViewById(R.id.btn_name);
				btn_name.setText(t.getTags());
				ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(
						ViewGroup.MarginLayoutParams.WRAP_CONTENT,
						ViewGroup.MarginLayoutParams.WRAP_CONTENT);
				layoutParams.setMargins(5, 5, 5, 5);
				innerView.setLayoutParams(layoutParams);
				holder.addViewLinearLayout(R.id.tag,innerView);
			}
		}


		// holder.removeAllViews(R.id.fabu_flowLayout02);
		// for (int i = 0; i < str.length; i++) {
		// View view = LayoutInflater.from(MyApplcation.ctx).inflate(T
		// R.layout.item_biaoqian, null);
		// final TextView btn_name = (TextView) view
		// .findViewById(R.id.btn_name);
		// btn_name.setText(str[i]);
		//
		// holder.addView(R.id.fabu_flowLayout02, view);
		// }
//		holder.setOnClickListener(R.id.fuyong, position, new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				money = t.getEntrustMoney();
//				tempContractNo=t.getContractNo();
//				mCameraPopupWindow = new WriteZhangHaoPopupWindow(activity,
//						onclickListener);
//				pass = (EditText) mCameraPopupWindow.getContentView()
//						.findViewById(R.id.pass);
//				mCameraPopupWindow.setBackgroundDrawable(new BitmapDrawable());
//				mCameraPopupWindow.setFocusable(true);
//				mCameraPopupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
//				mCameraPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//				mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
//
//			}
//		});
		holder.setOnClickListener(R.id.shuaxin, position,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						tempHouseNo=t.getHouseNo();
						showDelDialog(4);
					}
				});
		holder.setOnClickListener(R.id.xuanyuyue, position,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						TextView textView=((TextView) v);
						if(textView.getText().toString().equals("删除")){
							tempHouseNo = t.getHouseNo();
							showDelDialog(1);//删除框

						}else {
							Intent intent = new Intent(activity,
									ActivityEditHouse.class);
							intent.putExtra("uid", uid);
							intent.putExtra("house_no", t.getHouseNo());
							activity.startActivity(intent);
						}
					}
				});
		holder.setOnClickListener(R.id.renzheng, position,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						TextView textView = (TextView) v;
						if (textView.getText().toString().equals("认证")) {
							if(t.getTagId().equals("1")){
								Intent intent = new Intent(activity,
										AuthorIngActivity.class);
								activity.startActivityForResult(intent,WodeFangyYuanAdapter_REQUEST);
							}else{
								Intent intent = new Intent(activity,
										ActivityRenZheng.class);
								intent.putExtra("house_no", t.getHouseNo());
								intent.putExtra("address", t.getAddressDetail());
								intent.putExtra("role", role);
								activity.startActivity(intent);
							}
						} else if (textView.getText().toString().equals("认证中")){
							Intent intent = new Intent(activity,
									AuthorIngActivity.class);
							activity.startActivityForResult(intent,WodeFangyYuanAdapter_REQUEST);
						}
					}
				});
		holder.setOnClickListener(R.id.xiajia, position, new OnClickListener() {

			@Override
			public void onClick(View v) {
				TextView textView = (TextView) v;
				tempHouseNo = t.getHouseNo();
				if (textView.getText().toString().equals("下架")) {
					showDelDialog(3);

				} else {
					showDelDialog(2);

				}
			}
		});
		holder.setOnClickListener(R.id.xuanzuke, position,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						TextView textView = (TextView) v;
						// if (textView.getTag().toString().equals("0")) {
						// ByAlert.alert("请先去房源认证哦！");
						// } else {

						if (Integer.parseInt(t.getApply()) > 0) {
							Intent intent = null;
							if (textView.getText().equals("查看租客信息")) {
								intent = new Intent(activity,
										YuYueZuKeDetail.class);
								intent.putExtra("house_no", t.getHouseNo());
								activity.startActivity(intent);
							} else {
								intent = new Intent(activity,
										ActivityXuanZuKe.class);
								intent.putExtra("house_no", t.getHouseNo());
								activity.startActivity(intent);
							}
						} else {
							ByAlert.alert("当前没有租客申请");
						}
						// }
					}
				});

	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == HousePresenter.xiaJia_success) {
				Iterator<WoDeFangYuanBean> iterator = datas.iterator();
				while (iterator.hasNext()) {
					WoDeFangYuanBean woDeFangYuanBean = (WoDeFangYuanBean) iterator
							.next();
					if (tempHouseNo.equals(woDeFangYuanBean.getHouseNo())) {
						woDeFangYuanBean.setStatus("2");
						notifyDataSetChanged();
						break;
					}
				}
				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == HousePresenter.xiaJia_fail) {
				ByAlert.alert(entity.getData());

			} else if (entity.getEventType() == HousePresenter.refrshHouse_success) {

				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == HousePresenter.refrshHouse_fail) {
				ByAlert.alert(entity.getData());
//				loadDialog.dismiss();
				} else if (entity.getEventType() == HousePresenter.shangJia_fail) {

					ByAlert.alert(entity.getData());
				} else if (entity.getEventType() == HousePresenter.shangJia_success) {
					Iterator<WoDeFangYuanBean> iterator = datas.iterator();
					while (iterator.hasNext()) {
						WoDeFangYuanBean woDeFangYuanBean = (WoDeFangYuanBean) iterator
								.next();
						if (tempHouseNo.equals(woDeFangYuanBean.getHouseNo())) {
							iterator.remove();
							notifyDataSetChanged();
							break;
						}
					}

				}else if(entity.getEventType() == HousePresenter.deleteHouse_success){
				Iterator<WoDeFangYuanBean> iterator = datas.iterator();
				while (iterator.hasNext()) {
					WoDeFangYuanBean woDeFangYuanBean = (WoDeFangYuanBean) iterator
							.next();
					if (tempHouseNo.equals(woDeFangYuanBean.getHouseNo())) {
						iterator.remove();
						woDeFangYuanBean.setStatus("1");
						notifyDataSetChanged();
						break;
					}
				}

				ByAlert.alert(entity.getData());
			}else if(entity.getEventType() == HousePresenter.deleteHouse_fail){
				ByAlert.alert(entity.getData());

			}
		}
		try {

			uiAlertView.dismiss();
		}catch (Exception e){

		}
		try {
			loadDialog.dismiss();
		}catch (Exception e){

		}
	}

	protected OnClickListener onclickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v.getId() == R.id.btn_ok) {
				String phone = pass.getText().toString();
				if (phone.equals("")) {
					ByAlert.alert("请输入对方账户");
					return;
				}
				mCameraPopupWindow.dismiss();
				Intent intent = new Intent(activity, ActivityFuYongOne.class);
				intent.putExtra("phone", phone);
				intent.putExtra("money", money);
				if(role.equals("fangdong")){//为房东时不需要传contractNo

				}else{
					intent.putExtra("contractNo", tempContractNo);
				}
				activity.startActivity(intent);

			} else if (v.getId() == R.id.btn_cancel) {
				mCameraPopupWindow.dismiss();
			}
		}
	};

	/**
	 *
	 * @param type 1、删除房源  2、上架房源  3、下架房源   4、刷新房源
     */
	private void showDelDialog(final int type) {
		uid = SPUtils.get(activity, null, SPContants.USER_ID, "") + "";
		uiAlertView = new UIAlertView(activity, "温馨提示！", "是否继续操作？", "是", "取消");
		uiAlertView.show();

		uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {

			public void doRight () {//取消
				uiAlertView.dismiss();

			}

			public void doLeft() {//确定操作
				loadDialog=new LoadingDialog();
				loadDialog.setMsg("请求中,请稍后");
				loadDialog.setCancelable(false);
				loadDialog.show(activity.getFragmentManager(),"");
				switch (type){
					case 1:
						housePresenter.deleteHouse(uid,tempHouseNo);
						break;
					case 2:
						housePresenter.shangjia(uid, tempHouseNo);
						break;
					case 3:
						housePresenter.xiajia(uid, tempHouseNo);
						break;
					case 4:
						housePresenter.refreshHouse(uid, tempHouseNo);
						break;
				}

				uiAlertView.dismiss();

			}
		});
	}
}
